package jnpf.base.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ExcelImporter {

    public static <T> List<T> importExcel(String filePath, Class<T> clazz) throws IOException {
        List<T> data = new ArrayList<>();
        EasyExcel.read(filePath, clazz, new ExcelDataListener<>(data)).sheet().doRead();
        return data;
    }



    public static <T> List<T> importExcel(String filePath, Class<T> clazz,Integer sheetIndex) throws IOException {
        List<T> data = new ArrayList<>();
        EasyExcel.read(filePath, clazz, new ExcelDataListener<>(data)).sheet(sheetIndex).doRead();
        return data;
    }


    private static class ExcelDataListener<T> extends AnalysisEventListener<T> {

        private List<T> data;

        public ExcelDataListener(List<T> data) {
            this.data = data;
        }

        @Override
        public void invoke(T object, AnalysisContext context) {
            data.add(object);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            // Do nothing
        }
    }
}
